/**
 * @param {string} number
 * @return {string}
 */
var reformatNumber = function (number) {
  let  temp=''
  if(number.length<=3) return number
  for (let i = 0; i < number.length; i++) {
    // console.log(number[i]=='-');
    if (number[i] != '-' && number[i] !=' ') {
      temp +=number[i]
    }
  }
  let res = ''
  let count1 = 0
  let count2 = 0
  if (temp.length % 3 == 1) {
    for (let i = 0; i < temp.length - 4; i++) {
      if (count1 != 3) {
        res += temp[i]
        count1++
      } else {
        count1 = 1
        res += '-'+temp[i]
      }
    }
    res+='-'
    for (let i = temp.length - 4; i < temp.length; i++) {
      if (count2 != 2) {
        res += temp[i]
        count2++
      } else {
        count2 = 1
        res += '-'+ temp[i]
      }
    }
  } else if (temp.length % 3 == 0) {
    for (let i = 0; i < temp.length; i++) {
      if (count1 != 3) {
        res += temp[i]
        count1++
      } else {
        count1 = 0
        res += '-'+ temp[i]
      }
    }
  } else {
    for (let i = 0; i < temp.length-2; i++) {
      if (count1 != 3) {
        res += temp[i]
        count1++
      } else {
        count1 = 1
        res += '-'+ temp[i]
      }
    }
    res += '-'+temp.slice(temp.length-2)
  }

  return res
}

console.log(reformatNumber('189-0469-2731  5107289'));